package org.laowenchao.server;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.laowenchao.client.model.Folder;
import org.laowenchao.client.rpc.ArticleService;
import org.laowenchao.dao.ArticleDao;
import org.laowenchao.pojo.Article;

import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ArticleServiceImpl extends RemoteServiceServlet implements ArticleService{

	@Override
	public void addArticle(String title, String content) throws IllegalArgumentException {
		ArticleDao articleDao = new ArticleDao();
		
		Article article = new Article(title,content,new Date());
		articleDao.save(article);
	}

	@Override
	public Folder getFolder() throws IllegalArgumentException {
		
		ArticleDao articleDao = new ArticleDao();
		List<Article> articleList = articleDao.getArticles();
		
		Folder root = new Folder(Folder.ROOT,"root");
		
		Folder first = new Folder(Folder.ID,"所有文章",root); 
		
		Folder defaultType = new Folder(Folder.ID,"默认分类",first);
		
		for(int i=0;i<articleList.size();i++)
		{
			defaultType.add(new Folder(articleList.get(i).getId(),articleList.get(i).getTitle()));
		}
		
		Folder second = new Folder(Folder.ID,"日志归档",root); 
		
		Calendar c1 = Calendar.getInstance();
		
		for(int i=0;i<articleList.size();i++)
		{
			Article article = articleList.get(i);
			c1.setTime(article.getDate());
			Folder date = new Folder(Folder.ID,
					c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+"月",
					second);
			date.add(new Folder(article.getId(),article.getTitle()));
			for(int j=i+1;j<articleList.size();j++)
			{
				Article nextArticle = articleList.get(j);
				Calendar c2 = Calendar.getInstance();
				c2.setTime(nextArticle.getDate());
				if(c1.get(Calendar.YEAR)==c2.get(Calendar.YEAR)
						&&(c1.get(Calendar.MONTH)==c2.get(Calendar.MONTH)))
				{
					date.add(new Folder(nextArticle.getId(),nextArticle.getTitle()));
					i = j;
				}
				else 
				{
					break;
				}
			}

		}
	
		return root;
	}

	@Override
	public String[] getArticleById(Long id) {
		ArticleDao articleDao = new ArticleDao();
		Article article = articleDao.getArticleById(id);
		String content = article.getContent();
		
		String date = article.getDate().toLocaleString();
		
		System.out.println(content);
		return new String[]{content,date};
		
	}

}
